import { 
  createSlice,
 } from "@reduxjs/toolkit";
import { useSelector } from "react-redux";
import {postLogin ,getInfo,postLogout} from "@/api/auth";

const authSlice = createSlice({
  name:'auth',
  initialState:{
    token:localStorage.getItem('token'),
    // 1. 存储个人信息的状态
    info: localStorage.info?JSON.parse(localStorage.info):{},
    isLoading:false // 是否加载完
  },
  reducers:{
    // 更新登录状态  payload是改变数据
    upToken(state , {payload}){
      console.log(payload);
      console.log(state.token);
      console.log(localStorage.token);
      state.token = localStorage.token = payload // 把payload赋值给 state.token  localStorage.token 
    },
    // . 更新个人信息状态
    upInfo(state,{payload}){
      localStorage.setItem('info',JSON.stringify(payload))
      state.info = payload
    },
     //-清空Storage以及state.info,state.token
     clearState(state,{payload}){
      localStorage.clear();
      state.info ={};
      state.token = payload;
  },
  }
})

// . 声明更新的方法
const {upToken , upInfo, clearState} = authSlice.actions

//   请求登录 方式1
export const postLoginAsync = (values:any) =>{
  return async (dispatch:any) => {
    const result = await postLogin(values)
    console.log(result);// 请求成功的数据
    dispatch(upToken(result.data))// 改变token值
    return result
  }
}

// 请求登录 方式2 
// export const postLoginAsync2 = createAsyncThunk("aaaa",async (values:any)=>{
//   const result =  await postLogin(values);
//   return result;
// });

// . 获取个人信息
export const getInfoAsync = ()=>(
  async(dispatch:any,getState:any) =>{
    const state = getState()
    // 判断是否获取过个人信息
    if(state.auth.info.name) return
    const reslut = await getInfo()
    dispatch(upInfo({
      name:reslut.data.name,
      avatar:reslut.data.avatar
    }))
  }
)

// 退出登录
export const postLogoutAsync = () =>(
  async(dispatch:any) =>{
    const result = await postLogout()
    dispatch(clearState(null))
  }
)

export const useSelectorAuth= () =>useSelector((state:any)=>state.auth)
export default authSlice.reducer